package com.fc.commons;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import com.alibaba.fastjson.JSON;
import com.fc.commons.logger.UtilLogger;

public class HttpUtil {

	private static final String DEFAULT_ENCODE = "utf-8";

	public static String doPost(String url, JSON param) throws Exception {
		OutputStream out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			// conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = conn.getOutputStream();
			// 发送请求参数
			out.write(JsonUtils.object2Bytes(param));
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODE));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	protected void initSSL() {
		try {
			KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
			TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
			kmf.init(loadKeyStore(), KEYSTORE_PASSWORD.toCharArray());
			tmf.init(loadKeyStore());
			SSLContext sslContext = SSLContext.getInstance("SSL");
			sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
			HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

			// HostnameVerifier hostnameVerifier = new SimpleHostnameVerifier();
			// HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
		} catch (Exception e) {
			UtilLogger.instance().getLogger().error("Init SSL error", e);
		}
	}

	final String KEYSTORE_FILE = "证书";

	final String KEYSTORE_PASSWORD = "密码";

	final String KEYSTORE_ALIAS = "alias";

	/**
	 * load证书
	 * 
	 * @return
	 */
	private KeyStore loadKeyStore() {
		KeyStore ks = null;
		FileInputStream fis = null;
		try {
			ks = KeyStore.getInstance("PKCS12");
			fis = new FileInputStream(KEYSTORE_FILE);
			char[] nPassword = null;
			if ((KEYSTORE_PASSWORD == null) || KEYSTORE_PASSWORD.trim().equals("")) {
				nPassword = null;
			} else {
				nPassword = KEYSTORE_PASSWORD.toCharArray();
			}
			ks.load(fis, nPassword);
		} catch (KeyStoreException e) {
			UtilLogger.instance().getLogger().error(e.getMessage(), e);
		} catch (FileNotFoundException e) {
			UtilLogger.instance().getLogger().error(e.getMessage(), e);
		} catch (NoSuchAlgorithmException e) {
			UtilLogger.instance().getLogger().error(e.getMessage(), e);
		} catch (CertificateException e) {
			UtilLogger.instance().getLogger().error(e.getMessage(), e);
		} catch (IOException e) {
			UtilLogger.instance().getLogger().error(e.getMessage(), e);
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					UtilLogger.instance().getLogger().error(e.getMessage(), e);
				}
			}
		}
		return ks;
	}

}
